package com.ctgu.demo03.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctgu.demo03.entity.StocksEntity;
import com.ctgu.demo03.service.StocksService;
import com.ctgu.demo03.mapper.StocksMapper;
import com.ctgu.demo03.utils.ApiResult;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
* @author Alex2
* @description 针对表【t_stocks】的数据库操作Service实现
* @createDate 2025-03-12 08:50:13
*/
@Service
public class StocksServiceImpl extends ServiceImpl<StocksMapper, StocksEntity>
    implements StocksService {

    /**
     * @Author: Alex
     * @Description:添加库存
     */
    @Override
    public ApiResult insertStock(String name, Integer stock) {
        StocksEntity stocks = lambdaQuery().eq(StocksEntity::getName, name).one();
        if (stocks != null) {
            return ApiResult.error("该库存已存在，插入失败");
        }
        StocksEntity stocksEntity = new StocksEntity(null, name, stock);
        boolean save = save(stocksEntity);
        if (!save) {
            return ApiResult.error("插入失败");
        } else {
            return ApiResult.success("插入成功");
        }
    }

    /**
     * @Author: Alex
     * @Description: CAS实现乐观锁
     */
    @Override
    public ApiResult fetchVoucher(Integer id) {
        StocksEntity stocks = lambdaQuery().eq(StocksEntity::getId, id).one();
        if (stocks == null || stocks.getStock() <= 0) {
            return ApiResult.error("库存不足");
        }
        StocksService stocksServiceProxy = (StocksService) AopContext.currentProxy();
        boolean update = stocksServiceProxy.updateStock(id);
        if (!update) {
            return ApiResult.error("库存不足");
        }
        return ApiResult.success("更新成功");
    }

    @Transactional
    public boolean updateStock(Integer id) {
        // 先查询再更新，存在超卖问题
//        lambdaUpdate().eq(StocksEntity::getId, id)
//                .set(StocksEntity::getStock, stocks.getStock() - 1)  // 先查询 stockValue 再减
//                .gt(StocksEntity::getStock, 0)
//                .update();

        // 不查询，不存在超卖问题
        return lambdaUpdate()
                .eq(StocksEntity::getId, id)
                .setSql("stock = stock - 1")
                .gt(StocksEntity::getStock, 0)
                .update();
    }
}